package com.swiftride.controller.manager;

import cn.dev33.satoken.annotation.SaIgnore;
import com.swiftride.result.R;
import com.swiftride.template.CosTemplate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Tag(name = "cos文件上传", description = "cos文件上传接口")
@RestController
@RequestMapping("/cos")
public class cosController {

    @Autowired
    private CosTemplate cosTemplate;

    @Operation(summary = "文件上传", description = "文件上传接口")
    @Parameter(name = "folder", description = "文件夹")
    @Parameter(name = "uploadFile", description = "上传文件临时路径", required = true)
    @PostMapping(value = "/uploadFile/{folder}")
    @SaIgnore
    public R<String> uploadFile(@PathVariable("folder") String folder, MultipartFile file) {
        return getStringR(folder, file);
    }

    @Operation(summary = "微服务之间文件上传", description = "微服务之间文件上传接口")
    @Parameter(name = "folder", description = "文件夹")
    @Parameter(name = "file", description = "文件", required = true)
    @PostMapping(value = "/ServiceUploadFile/{folder}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SaIgnore
    public R<String> serviceUploadFile(@PathVariable("folder") String folder, @RequestPart("file") MultipartFile file) {
        return getStringR(folder, file);
    }

    private R<String> getStringR(@PathVariable("folder") String folder, MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            String filePath = cosTemplate.uploadFile(inputStream, folder, fileName);
            return R.success(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
